# 导入必要的库
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# 1. 加载数据集
# ---------------------------------------------
iris = load_iris()
X = iris.data  # 特征矩阵（4个特征：萼片长、萼片宽、花瓣长、花瓣宽）
y = iris.target  # 目标变量（3种鸢尾花类别）

# 可选：将数据转换为DataFrame方便查看（非必须）
df = pd.DataFrame(X, columns=iris.feature_names)
df['target'] = y
print("数据集前5行：")
print(df.head())

# 2. 划分训练集和测试集
# ---------------------------------------------
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 3. 归一化/标准化（以Min-Max为例）
# ---------------------------------------------
# 初始化归一化器（注意：仅用训练集拟合）
# scaler = MinMaxScaler() #最大值-最小值归一化
scaler = StandardScaler() #标准归一化
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)  # 测试集用相同的参数转换


# 4. 训练k-NN模型
# ---------------------------------------------
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train_scaled, y_train)

# 5. 评估模型
# ---------------------------------------------
accuracy = knn.score(X_test_scaled, y_test)
print(f"模型准确率：{accuracy:.2f}")